package com.lagou.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.lagou.bean.UploadResult;
import com.lagou.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileUploadService {
    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;

    // 允许上传的格式
//    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", "jpeg", ".gif", ".png"};
    private static final String[] IMAGE_TYPE = new String[]{".jpg", "jpeg", ".png"};

    public UploadResult upload(MultipartFile multipartFile) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type: IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }

        UploadResult uploadResult = new UploadResult();
        if (!isLegal) {
            uploadResult.setStatus("error");
            uploadResult.setResponse("文件类型错误");
            return uploadResult;
        }

        if (multipartFile.getSize() > 200) {
            uploadResult.setStatus("error");
            uploadResult.setResponse("文件大小超过5M");
            return uploadResult;
        }

        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            uploadResult.setStatus("error");
            return uploadResult;
        }

        uploadResult.setStatus("done");
        uploadResult.setName(aliyunConfig.getUrlPrefix() + filePath);
        uploadResult.setUid(filePath);
        return uploadResult;
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    public UploadResult downloadFile(String bucket, String fileName)
    {
        String[] parts = fileName.split("/");
        String dest = parts[parts.length - 1];
        ossClient.getObject(new GetObjectRequest(bucket, fileName), new File(dest));
        UploadResult uploadResult = new UploadResult();
        uploadResult.setResponse(dest);

        return uploadResult;
    }

    public UploadResult deleteFile(String bucket, String fileName)
    {
        ossClient.deleteObject(bucket, fileName);
        UploadResult uploadResult = new UploadResult();
        uploadResult.setResponse("Delete successfully");

        return uploadResult;
    }

}
